package org.jeecg.modules.car.controller;

import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.net.URLDecoder;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import org.apache.ibatis.annotations.Param;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.QRCodeUtil;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.common.util.StringUtils;
import org.jeecg.common.util.oConvertUtils;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.entity.car.CarGate;
import org.jeecg.modules.car.entity.CarParkInfo;
import org.jeecg.modules.car.service.ICarGateService;
import org.jeecg.modules.car.service.ICarParkInfoService;
import org.jeecg.modules.car.service.impl.ForeignCarJGSService;
import org.jeecg.vo.car.ForeignCarGateResp;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

 /**
 * @Description: 车场通道
 * @Author: jeecg-boot
 * @Date:   2021-05-26
 * @Version: V1.0
 */
@Slf4j
@Api(tags="车场通道")
@RestController
@RequestMapping("/b/car/carChannel")
public class CarGateController {
	@Autowired
	private ICarGateService carChannelService;
	@Autowired
	private ForeignCarJGSService foreignCarJGSService;
	@Autowired
	private ICarParkInfoService carParkInfoService;
	
	/**
	  * 分页列表查询
	 * @param carGate
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "车场通道-分页列表查询")
	@ApiOperation(value="车场通道-分页列表查询", notes="车场通道-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<CarGate>> queryPageList(CarGate carGate,
                                                @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                HttpServletRequest req) {
		Result<IPage<CarGate>> result = new Result<IPage<CarGate>>();
		QueryWrapper<CarGate> queryWrapper = QueryGenerator.initQueryWrapper(carGate, req.getParameterMap());
		Page<CarGate> page = new Page<CarGate>(pageNo, pageSize);
		IPage<CarGate> pageList = carChannelService.page(page, queryWrapper);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}
	
	/**
	  *   添加
	 * @param carGate
	 * @return
	 */
	@AutoLog(value = "车场通道-添加")
	@ApiOperation(value="车场通道-添加", notes="车场通道-添加")
	@PostMapping(value = "/add")
	public Result<CarGate> add(@RequestBody CarGate carGate) {
		Result<CarGate> result = new Result<CarGate>();
		try {
			carChannelService.save(carGate);
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}
	@RequestMapping("getGate")
    public Result<CarGate> getGate(String parkId){
		Result<CarGate> carChannelResult = new Result<>();
		if (StringUtils.isEmpty(parkId)){
			return Result.error("请选择车场");
		}
		CarParkInfo parkInfo = carParkInfoService.getById(parkId);
		if (parkInfo == null || StringUtils.isEmpty(parkInfo.getOutSysId())){
			return Result.error("该车场未同步");
		}
		LoginUser loginUser = SsoUtil.getLoginUser();
		String tenantId = loginUser.getTenantId();
		Result<List<ForeignCarGateResp>> parkGate = foreignCarJGSService.getParkGate(parkInfo.getOutSysId());
		if (parkGate.getCode() == 500){
			return Result.error("获取外部信息失败");
		}
		List<ForeignCarGateResp> gateList = parkGate.getResult();
		if (null != gateList){
			String oldGateList = JSON.toJSONString(gateList);
			List<CarGate> channelList = JSON.parseArray(oldGateList, CarGate.class);
			for (CarGate carGate :channelList){
				carGate.setId(String.valueOf(IdWorker.getId()));
				carGate.setTenantId(tenantId);
				carGate.setProjectId(parkInfo.getProjectId());
				carGate.setParkName(parkInfo.getParkName());
				carGate.setParkId(parkId);
			}
			 try {
				carChannelService.saveCarGate(channelList);
				carChannelResult.setSuccess(true);
				carChannelResult.setMessage("操作成功");
			}catch (Exception e){
				return Result.error("系统错误");
			}
		}
		return carChannelResult;
	}

	/**
	  *  编辑
	 * @param carGate
	 * @return
	 */
	@AutoLog(value = "车场通道-编辑")
	@ApiOperation(value="车场通道-编辑", notes="车场通道-编辑")
	@PutMapping(value = "/edit")
	public Result<CarGate> edit(@RequestBody CarGate carGate) {
		Result<CarGate> result = new Result<CarGate>();
		CarGate carGateEntity = carChannelService.getById(carGate.getId());
		if(carGateEntity ==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = carChannelService.updateById(carGate);
			//TODO 返回false说明什么？
			if(ok) {
				result.success("修改成功!");
			}
		}
		
		return result;
	}
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "车场通道-通过id删除")
	@ApiOperation(value="车场通道-通过id删除", notes="车场通道-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		try {
			carChannelService.removeById(id);
		} catch (Exception e) {
			log.error("删除失败",e.getMessage());
			return Result.error("删除失败!");
		}
		return Result.ok("删除成功!");
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "车场通道-批量删除")
	@ApiOperation(value="车场通道-批量删除", notes="车场通道-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<CarGate> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<CarGate> result = new Result<CarGate>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.carChannelService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@AutoLog(value = "车场通道-通过id查询")
	@ApiOperation(value="车场通道-通过id查询", notes="车场通道-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<CarGate> queryById(@RequestParam(name="id",required=true) String id) {
		Result<CarGate> result = new Result<CarGate>();
		CarGate carGate = carChannelService.getById(id);
		if(carGate ==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(carGate);
			result.setSuccess(true);
		}
		return result;
	}

  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
      // Step.1 组装查询条件
      QueryWrapper<CarGate> queryWrapper = null;
      try {
          String paramsStr = request.getParameter("paramsStr");
          if (oConvertUtils.isNotEmpty(paramsStr)) {
              String deString = URLDecoder.decode(paramsStr, "UTF-8");
              CarGate carGate = JSON.parseObject(deString, CarGate.class);
              queryWrapper = QueryGenerator.initQueryWrapper(carGate, request.getParameterMap());
          }
      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      }

      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      List<CarGate> pageList = carChannelService.list(queryWrapper);
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "1列表");
      mv.addObject(NormalExcelConstants.CLASS, CarGate.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("1列表数据", "导出人:Jeecg", "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
  }


	 public InputStream bufferedImageToInputStream(BufferedImage image){
		 ByteArrayOutputStream os = new ByteArrayOutputStream();
		 try {
			 ImageIO.write(image, "png", os);
			 InputStream input = new ByteArrayInputStream(os.toByteArray());
			 return input;
		 } catch (IOException e) {
			 log.error("提示:",e);
		 }
		 return null;
	 }
	 /**
	  * 批量生成二维码
	  */
	 @GetMapping("generateBatchRr")
	 @ResponseBody
	 public void generateBatchRr(HttpServletResponse response,@Param("parkId") String parkId){
	 	 String url = "";
		 //获取列表
		 List<CarGate> carGates = carChannelService.getByInParkId(parkId);
		 response.setContentType("application/octet-stream");
		 response.setHeader("Content-Disposition", "attachment; filename=QrCode-" + System.currentTimeMillis() + ".zip");// 压缩包名
		 ZipOutputStream zos = null;
		 try {
			 zos = new ZipOutputStream(response.getOutputStream());
			     for (CarGate carGate:carGates){
					if (carGate.getIostate() == 1){
						url = "https://b.ian9.cn/cim-tencent/jump/noPlateEntrance?outParkId="+ carGate.getOutSysId()+"&gateId="+carGate.getGateId();
					}else if (carGate.getIostate() ==2 ){
						url = "https://b.ian9.cn/cim-tencent/jump/noPlate?outParkId=" + carGate.getOutSysId()+"&gateId="+carGate.getGateId();
					}
				 BufferedImage qrCode = QRCodeUtil.createImage(url, null, true);
				 InputStream inputStream = bufferedImageToInputStream(qrCode);
				 zos.putNextEntry(new ZipEntry(carGate.getGateName() + ".JPEG"));
				 int temp = 0;
				 while ((temp = inputStream.read()) != -1) {
					 zos.write(temp);
				 }
				 inputStream.close(); // 关闭输入流
			 }
		 } catch (Exception e) {
			 e.printStackTrace();
		 } finally {
			 try {
				 if (null != zos) {
					 zos.flush();
					 zos.close();
				 }
			 } catch (IOException e) {
				 e.printStackTrace();
			 }
		 }
	 }

	 /**
	  * 生成图片流打包案例 -- 2021-06-01
	  * @param response
	  * @throws Exception
	  */
	 @GetMapping(value = "/generateQR")
	 @ResponseBody
	 public   void getCode(HttpServletResponse response, @Param("parkId") String parkId,@Param("gateId") String gateId,
						   @Param("iostate")Integer iostate) throws Exception {
	  	String url = "";
		 CarParkInfo carInfo = carParkInfoService.getByParkId(parkId);
		 if (iostate == 1){
         	//进口地址
			   url = "https://b.ian9.cn/cim-tencent/jump/noPlateEntrance?outParkId="+ carInfo.getOutSysId()+"&gateId="+gateId;
		    }else if (iostate == 2){
         	   url = "https://b.ian9.cn/cim-tencent/jump/noPlate?outParkId=" + carInfo.getOutSysId()+"&gateId="+gateId;
		   }else if(iostate ==3){
        	   url = "https://b-test.ian9.cn/cim-tencent/park/qrCode";
		}
         response.setContentType("image/jpg");
		 response.setHeader("Pragma", "no-cache");
		 response.setHeader("Cache-Control", "no-cache");
		 response.setDateHeader("Expires", 0);
		 OutputStream stream = response.getOutputStream();
		 //获取一个二维码图片
		 BitMatrix bitMatrix = QRCodeUtil.createImage1(url, true);
		 //以流的形式输出到前端
		  MatrixToImageWriter.writeToStream(bitMatrix , "jpg" , stream);
	 }

}
